
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_device_info_plugin/flutter_device_info_plugin.dart';
import 'package:furaha_mkopo/commonTool/fm_language_tool.dart';
import 'package:furaha_mkopo/page/base/fm_base_page_widget.dart';
import 'package:furaha_mkopo/page/home/orderDetail/emergency/fm_emergency_cell_widget.dart';
import 'package:geolocator_platform_interface/src/models/position.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import '../../../../commonTool/fm_color_tool.dart';
import '../../../../commonTool/fm_screen_tool.dart';
import '../../../../commonUI/fm_bottom_button.dart';
import '../../../../commonUI/fm_custon_nav_bar_widget.dart';
import '../../../../commonUI/fm_detail_step_widget.dart';
import '../../../../commonUI/fm_progress_hud.dart';
import '../../../dialog/single/fm_single_radio_page.dart';
import 'fm_emergency_controller.dart';
import 'fm_emergency_model.dart';

class FMEmergencyPage extends FMBasePageWidget {

  String orderId;

  String? title;

  bool? isOldPage;

  FMEmergencyPage({super.key,required this.orderId,this.title,this.isOldPage});

  @override
  State<FMEmergencyPage> createState() => _FMEmergencyPageState();
}

class _FMEmergencyPageState extends FMBasePageState<FMEmergencyPage> {

  final controller = Get.put(FMEmergencyController());

  @override
  void initState() {
    super.initState();

    Future.delayed(const Duration(milliseconds: 500),(){
      controller.refreshData(widget.orderId);
    });
    FMProgressHud.showLoading();
  }

  @override
  void dispose() {
    Get.delete<FMEmergencyController>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: FMColorTool.color("#54E041"),
      resizeToAvoidBottomInset: false,
      body: GetBuilder<FMEmergencyController>(builder: (controller){
        return _bodyWidget();
      }),
    );
  }

  Widget _bodyWidget() {
    return GestureDetector(
      onTap: (){},
      child: Stack(
        children: [
          _topWidget(),
          _contentWidget(),
          _bottomWidget()
        ],
      ),
    );
  }

  Widget _topWidget() {
    return Positioned(
      top: FMScreenTool.topPadding(context),
      left: 0,
      right: 0,
      child: FMCustomNavBarWidget(
          title: widget.title ?? ""
      ),
    );
  }

  Widget _contentWidget() {
    return Positioned(
      top: FMScreenTool.appBarHeight(context) + 14,
      bottom: FMScreenTool.bottomPadding(context) + 123,
      left: 16,
      right: 16,
      child: Container(
        decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage("assets/detail/emergency_bg.png"),
                fit: BoxFit.cover
            )
        ),
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 12,left: 11,right: 11),
              child: FMDetailStepWidget(
                  title: FMLanguageTool.getText("Step 4")
              ),
            ),
            const SizedBox(height: 16),
            _listWidget()
          ],
        ),
      ),
    );
  }

  Widget _listWidget() {
    if (controller.uploadData.isEmpty) {
      return Container();
    }else {
      return Expanded(
        child: SingleChildScrollView(
          child: Column(
            children: controller.uploadData.map((e){
              int index = controller.uploadData.indexOf(e);
              return Padding(
                padding: const EdgeInsets.only(bottom:14),
                child: FMEmergencyWidget(
                  title: controller.titleAtIndex(index),
                  relationTitle: controller.relationTitleAtIndex(index),
                  relationContent: controller.relationContentAtIndex(index),
                  relationPlaceHolder: controller.relationPlaceHolderAtIndex(index),
                  phoneTitle: controller.phoneTitleAtIndex(index),
                  phoneContent: controller.contactContentAtIndex(index),
                  phonePlaceHolder: controller.phonePlaceHolderAtIndex(index),
                  relationOnTap: (){
                    showRelationPop(index);
                  },
                  phoneOnTap: (){
                    showPhonePop(index);
                  },
                ),
              );
            }).toList(),
          ),
        ),
      );
    }
  }

  Widget _bottomWidget() {
    return Positioned(
      left: 38,
      right: 38,
      bottom: FMScreenTool.bottomPadding(context),
      child: FMBottomButton(
        title: "Submit",
        onTap: (){
          controller.saveData(context,widget.isOldPage);
        },
      ),
    );
  }

  void showRelationPop(int index) {

    List<FMEmergencyRetiredModel>? retired = controller.retiredListAtIndex(index);

    if (retired == null || retired.isEmpty) return;

    List<String> list = [];

    for (FMEmergencyRetiredModel model in retired) {
      if (model.planned != null && model.planned!.isNotEmpty) {
        list.add(model.planned!);
      }
    }

    Get.to(() => FMSingleRadioPage(
      selectData: controller.relationContentAtIndex(index),
      mList: list,
      onTap: (text){
        controller.updateRelationDic(index, text);
      },
    ),
        opaque: false, duration: Duration.zero);
  }

  void showPhonePop(int index) async {

    dynamic value = await FlutterDeviceInfoPlugin().openContact();

    String name = value["name"];

    String phone = value["phone"];
    
    controller.updateContactDic(index, name, phone);

    controller.reportTotalContactInfo();
  }

  @override
  void onLocationError(String error) {

  }

  @override
  void onLocationUpdated(Position position) {
    controller.position = position;
  }
}
